package com.ygqh.baby.service.impl;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.mapper.YgProductCommentMapper;
import com.ygqh.baby.model.SkuBasicData;
import com.ygqh.baby.model.YgProductCommentModel;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgProductComment;
import com.ygqh.baby.po.YgProductCommentExample;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class YgProductCommentServiceImpl implements YgProductCommentService {
    private Logger logger = Logger.getLogger(YgProductCommentServiceImpl.class);

    @Autowired
    private YgProductCommentMapper ygProductCommentMapper;

    @Autowired
    private SensitivewordFilter sensitivewordFilter;

    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private YgCouponService ygCouponService;
    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private YgUserService ygUserService;

    @Override
    public List<YgProductComment> find() {
        YgProductCommentExample example = new YgProductCommentExample();
        example.createCriteria().andStatusNotEqualTo(DataStatus.Delete.name());
        return ygProductCommentMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgProductCommentExample example = new YgProductCommentExample();
        example.createCriteria().andStatusNotEqualTo(DataStatus.Delete.name());
        return ygProductCommentMapper.countByExample(example);
    }

    @Override
    public YgProductComment findById(Long id) {
        return ygProductCommentMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(YgProductComment ygProductComment) {
        return ygProductCommentMapper.insertSelective(ygProductComment);
    }

    @Override
    public int update(YgProductComment ygProductComment) {
        return ygProductCommentMapper.updateByPrimaryKeySelective(ygProductComment);
    }

    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);
        int count = 0;
        for (Long id : ids) {
            YgProductComment ygProductComment = this.findById(id);
            ygProductComment.setStatus(DataStatus.Delete);
            count += ygProductCommentMapper.updateByPrimaryKeySelective(ygProductComment);
        }

        return count;
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public int saveOrUpdate(YgProductComment ygProductComment) {
        int r = 0;
        if (ygProductComment.getId() != null) {
            r = this.update(ygProductComment);
        } else {
            r = this.save(ygProductComment);
        }
        return r;
    }

    @Override
    public int updateBatchChechStatus(String checkBy, String checkStatus, Long[] ids) {
        return ygProductCommentMapper.updateBatchChechStatus(checkBy, checkStatus, ids);
    }

    @Override
    public ResultSet<YgProductComment> searchForHouTai(QueryInfo queryInfo, String checkBy, String productName, CheckStatus checkStatus, Date startDate,
                                                       Date endDate, Boolean isUserComment, String userName, Long orderId) {
        List<YgProductComment> list = ygProductCommentMapper.selectForHouTai(queryInfo, checkBy, productName, checkStatus, startDate, endDate, isUserComment,
                userName, orderId);
        int row = ygProductCommentMapper.countForHouTai(checkBy, productName, checkStatus, startDate, endDate, isUserComment, userName, orderId);
        return new ResultSet<YgProductComment>(row, list);
    }

    @Deprecated
    @Override
    public int commentOrderItem(Long orderId, Long userId, Long productId, Long skuId, String content, String imagesUrls, CommentTag[] commentTags,
                                Long couponDetailId) {
        YgUser user = ygUserService.findById(userId);

        return this.commentOrderItem(orderId, user, productId, skuId, content, imagesUrls, commentTags, couponDetailId);
    }

    @Override
    public int commentOrderItem(Long orderId, YgUser user, Long productId, Long skuId, String content, String imagesUrls, CommentTag[] commentTags,
                                Long couponDetailId) {

        Boolean commented = ygProductCommentMapper.isCommented(orderId, skuId);
        if (commented) {
            logger.warn("重复提交");
            return 0;
        }

        SkuBasicData sku = ygSkuService.getBasicDataBySkuId(skuId);

        YgProductComment comment = new YgProductComment();
        comment.setUserId(user.getId());
        comment.setGroupId(sku.getGroupId());
        comment.setNickName(user.getNickName());
        comment.setHeadImageUrl(user.getHeadImageUrl());
        comment.setProductCode(sku.getProductCode());
        comment.setProductName(sku.getProductName());
        comment.setShortName(sku.getShortName());
        comment.setSizeName(sku.getSizeName());
        comment.setOrderId(orderId);
        comment.setProductId(productId);
        comment.setSkuId(skuId);
        comment.setContent(content);
        comment.setImages(imagesUrls);
        comment.setCouponDetailId(couponDetailId);

        if (commentTags != null && commentTags.length > 0) {
            String tags[] = new String[commentTags.length];
            for (int i = 0; i < commentTags.length; i++) {
                tags[i] = commentTags[i].getTitle();
            }
            comment.setCommentTag(StringUtils.join(tags, ","));
        }
        comment.setCreateTime(new Date());
        Set<String> set = sensitivewordFilter.getSensitiveWord(content, 1);
        if (set.size() > 0) {
            comment.setCheckStatus(CheckStatus.Reject);
            comment.setCheckRemark("包含敏感词:" + set.toString());
            logger.debug("语句中包含敏感词的个数为：" + set.size() + "。包含：" + set);
        }
        int i = this.save(comment);
        Map<String, Long> map = ygOrderService.orderIsComment(orderId);
        if (map.get("itemCount").intValue() == map.get("commentCount").intValue()) {
            YgOrder ygOrder = new YgOrder();
            ygOrder.setOrderId(orderId);
            ygOrder.setCommentStatus(CommentStatus.Complete);
            ygOrderService.updateByOrderId(ygOrder);
        }

        return i;
    }

    @Cacheable(cacheNames = "redis", key = "'comment:pid_'+#productId")
    @Override
    public int count(Long productId) {
        int count = ygProductCommentMapper.count(null, productId);
        return count;
    }

    @Override
    public int replyProductComment(Long commentId, String replyContent, String replyBy) {

        YgProductComment record = new YgProductComment();
        record.setId(commentId);
        record.setReplyContent(replyContent);
        record.setReplyBy(replyBy);
        record.setReplyTime(new Date());
        return ygProductCommentMapper.updateByPrimaryKeySelective(record);
    }

    @Cacheable(cacheNames = "redis", key = "'comment:gid_'+#groupId")
    @Override
    public int commentCount(Long groupId) {
        return ygProductCommentMapper.count(groupId, null);
    }

    @Override
    public List<YgProductCommentModel> findModelList(QueryInfo queryInfo, Long groupId, Long productId) {
        return ygProductCommentMapper.selectModel(queryInfo, groupId, productId);
    }

    @Cacheable(cacheNames = "redis", key = "'comment:gid_'+#groupId")
    @Override
    public int countByCurrentGroup(Long groupId) {
        return ygProductCommentMapper.countByCurrentGroup(groupId);
    }

    @Override
    public List<YgProductCommentModel> findModelListByCurrentGroup(QueryInfo queryInfo, Long groupId) {
        return ygProductCommentMapper.selectModelListByCurrentGroup(queryInfo, groupId);
    }

    @Cacheable(cacheNames = "redis", key = "'commentlist:productCode_'+#productCode+'_'+#showAll+'_'+#queryInfo.start+'_'+#queryInfo.end")
    @Override
    public List<YgProductCommentModel> findModelListByProductCode(QueryInfo queryInfo, String productCode, boolean showAll) {
        return ygProductCommentMapper.selectModelListByProductCode(queryInfo, productCode, showAll);
    }

    @Cacheable(cacheNames = "redis", key = "'comment:product_'+#productCode+'_'+#showAll")
    @Override
    public int countByProductCode(String productCode, boolean showAll) {
        return ygProductCommentMapper.countByProductCode(productCode, showAll);
    }

}
